package GoodsActivityService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"sort"
)

// GetGoodsActivityByGoodsId 根据商品ID获取适合的活动列表
func GetGoodsActivityByGoodsId(ctx context.Context, goodsId int) ([]*entity.GoodsActivity, error) {
	// 找到活动时间内的活动
	var tmpList []*entity.GoodsActivity
	err := toolsDb.GetUnSafaTable(ctx, "goods_activity").Where(
		"ga.delete_at<1 AND ga.status = ? AND (ga.start_time <= UNIX_TIMESTAMP(NOW()) AND ga.end_time >= UNIX_TIMESTAMP(NOW()))",
		1,
	).As("ga").LeftJoin("goods_activity_rule gar", "gar.activity_id = ga.id").
		Where("ga.activity_type IN (1,2)").
		Fields("ga.*,gar.rules,gar.loop").Order("ga.sort DESC,ga.id ASC").
		Scan(&tmpList)
	if err != nil {
		return nil, err
	}
	//var gaList []*entity.GoodsActivity
	for k, item := range tmpList {
		// 去掉排除商品ID的活动
		if item.GoodsType == 2 && item.GoodsIds.Contains(goodsId) {
			// 在其中的
			tmpList = append(tmpList[:k], tmpList[k+1:]...)
		}
		// 如果活动不包含商品ID，也去掉
		if item.GoodsType == 1 && !item.GoodsIds.Contains(goodsId) {
			if len(tmpList) < 2 {
				// 判断如果不够减了，直接赋值
				tmpList = []*entity.GoodsActivity{}
			} else {
				tmpList = append(tmpList[:k], tmpList[k+1:]...)
			}
		}
		// 2022.06.12 添加判断，排除商品ID
		if item.ExcludeGoodsIds != nil && item.ExcludeGoodsIds.Contains(goodsId) {
			// 从数组里面删除本 item
			tmpList = append(tmpList[:k], tmpList[k+1:]...)
		}
	}

	// 按最优惠
	// 满减，取最高的那条优惠，算出比例
	// 满折，取最高的那条优惠的比例
	for _, item := range tmpList {
		item.DiscountRatio = clacDiscountRatio(item)
	}
	// 根据优惠排序
	sort.Slice(tmpList, func(i, j int) bool {
		return tmpList[i].DiscountRatio < tmpList[j].DiscountRatio
	})

	return tmpList, nil
}
